<script setup lang="ts">
import { UploadFilled } from '@element-plus/icons-vue'
import type { Action } from 'element-plus'
import type {
  CustomDialogInstance,
  MeasuringToolsInfo,
} from '@/types'
import { importMeasuringToolsAnnex } from '@/api/modules/measuringTools'

const props = defineProps<{
  formData: MeasuringToolsInfo
}>()
const emits = defineEmits<{
  (e: 'success'): void
}>()
const { $message, $confirm } = useCurrentInstance()

const fileList = ref<any[]>([])
const dialogRef = ref<CustomDialogInstance | null>(null)

async function open() {
  dialogRef.value?.open?.()
  await nextTick()
  dialogRef.value?.setSaving?.(false)
}
function close() {
  dialogRef.value?.close?.()
}

function onClose() {
  fileList.value.length = 0
}
async function clickConfirm(done: () => void) {
  if (fileList.value.length === 0) {
    $message.info('请选择文件！')
    done()
    return
  }

  let exceed = false
  let error = false
  unref(fileList).forEach((item: any) => {
    const file = item.raw
    if (file) {
      if (file.size > 2 * 1024 * 1024) {
        exceed = true
        $message.error(`${file.name}-文件大小不能超过2M`)
        done()
      }

      if (
        !['png', 'jpg', 'jpeg', 'pdf'].includes(
          file.type.split('/')[1],
        )
      ) {
        error = true
        $message.error('文件格式错误')
        done()
      }
    }
  })

  if (exceed || error)
    return

  try {
    await importMeasuringToolsAnnex(
      props.formData.id,
      fileList.value.map(item => item.raw),
    )
    done()
    $message.success('上传成功！')
    fileList.value.length = 0
    emits('success')
    close()
  }
  catch (error) {
    done()
  }
}
async function handlerBeforeClose(done: () => void) {
  if (fileList.value.length === 0) {
    done()
    return
  }
  const res: Action = await $confirm(
    '当前文件未保存，确认关闭吗？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  done()
}

function handleExceed() {
  $message.warning('一次最多上传10个文件')
}

// #endregion
defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    title="上传检测报告"
    need-saving
    width="600px"
    :before-close="handlerBeforeClose"
    @close="onClose"
    @confirm="clickConfirm"
  >
    <div class="margin-tb-xs">
      <p class="!margin-0">
        计量器具编号:
        <span>{{ formData.code }}</span>
      </p>
      <p class="margin-0 !margin-top-xs">
        计量器具名称:
        <span>{{ formData.name }}</span>
      </p>
    </div>
    <el-upload
      v-model:file-list="fileList"
      :http-request="() => void 0"
      drag
      multiple
      :limit="10"
      accept=".png,.jpg,.jpeg,.pdf"
      :auto-upload="false"
      :on-exceed="handleExceed"
    >
      <el-icon class="el-icon--upload">
        <UploadFilled />
      </el-icon>
      <div class="el-upload__text">
        拖拽上传或者
        <em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          仅支持
          <em>png、jpeg、pdf</em>
          文件格式;并且单个文件大小不能超过
          <em>2M</em>,
          一次最多上传10个文件。
        </div>
      </template>
    </el-upload>
  </CustomDialog>
</template>
